package top.maof.book.spider.develop.book.zongheng;

import lombok.Data;
import top.maof.book.model.Book;
import top.maof.book.model.Contents;
import top.maof.book.spider.develop.Split;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.model.AfterExtractor;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.HelpUrl;
import us.codecraft.webmagic.model.annotation.TargetUrl;

import java.util.Date;
import java.util.List;

/**
 * 纵横中文网
 */
@Data
@TargetUrl(value = {"http://book.zongheng.com/book/\\d+.html", "http://huayu.zongheng.com/book/\\d+.html"})
@HelpUrl(value = {"http://book.zongheng.com/store[\\w\\?=/&.]*", "http://book.zongheng.com/rank[\\w\\?=/&.]*",
        "http://huayu.zongheng.com/rank[\\w\\?=/&.]*", "http://huayu.zongheng.com/",
        "http://huayu.zongheng.com/category[\\w\\?=/&.]*"})
public class ZongHeng implements AfterExtractor, Split {

    public static final String CHARSET = "utf-8";

    @ExtractBy("//div[@class=book-info]/div[@class=book-name]/text()")
    private String name;

    @ExtractBy("//div[@class=book-author]/div[@class=au-name]/a/text()")
    private String author;

    @ExtractBy("//div[@class=book-img]/img/@src")
    private String img;

    @ExtractBy("//div[@class=book-label]/a[2]/text()")
    private String classify;

    @ExtractBy("//div[@class=book-label]/a[1]/text()")
    private String state;

    /**
     * 书收录时间
     */
    private Date insertDate = new Date();

    /**
     * 最新章节更新时间
     */
    private Date updateDate;

    /**
     * 书源站点名字
     */
    private String sourceSite;

    /**
     * 书源站点地址
     */
    private String sourceUrl;

    /**
     * 书开始连载时间
     */
    private Date startDate;
    @ExtractBy("//div[@class=book-dec]/p[1]/text()")
    private String synopsis;

    public static String getCHARSET() {
        return CHARSET;
    }


    @Override
    public Book getBook() {
        return new Book(null, name, author, img, classify, state,
                insertDate, updateDate, sourceSite, sourceUrl, startDate, synopsis);
    }

    @Override
    public Contents getContents() {
        return null;
    }

    @Override
    public void afterProcess(Page page) {
        this.author = this.author.trim();
        this.name = this.name.trim();
        this.sourceSite = "纵横中文网";
        if ("连载中".equals(state)) state = "连载";
        else if ("已完结".equals(state)) state = "完本";

        this.sourceUrl = page.getUrl().toString();
        List<String> all = page.getHtml().xpath("//a/@href").all();
        if (all != null && all.size() > 0) {
            for (String uri : all) {
                if (uri.contains("p1")) {
                    for (int i = 200; i <= 600; i++) {
                        page.addTargetRequest(uri.replace("p1", "p" + i));
                    }
                }
            }
        }

    }
}
